package com.wxy.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import jakarta.servlet.http.HttpServletResponse;
@Configuration
@EnableMethodSecurity
public class myUserDetailsConfig{
//	@Bean			//向内存中装入两个user对象用来校验username和password
//	public UserDetailsService userDetailsService(@Autowired PasswordEncoder passwordEncoder) {
//		InMemoryUserDetailsManager inMemoryUserDetailsManager=new InMemoryUserDetailsManager();
//		UserDetails user1=User.withUsername("jj").password(passwordEncoder.encode("jj"))
//				.roles("student")
//				.build();
//		UserDetails user2=User.withUsername("kk").password(passwordEncoder.encode("kk"))
//				.roles("teacher")
//				.authorities("teacher")
//				.build();
//		inMemoryUserDetailsManager.createUser(user1);
//		inMemoryUserDetailsManager.createUser(user2);
//		return inMemoryUserDetailsManager;
//	}
//	@Bean			//自定义用户必须配置密码加密
//	public PasswordEncoder passwordEncoder() {
//		return NoOpPasswordEncoder.getInstance();
//	}
	@Bean				//加密
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	//将登录的cookie信息存储在数据库中
	@Bean("repository")
	public PersistentTokenRepository tokenRepository(@Autowired DataSource dataSource) {
		JdbcTokenRepositoryImpl repository=new JdbcTokenRepositoryImpl();
//		//第一次执行时添加，创建数据表用来存储登录的cookie信息。
//		repository.setCreateTableOnStartup(true);
		repository.setDataSource(dataSource);
		return repository;
	}
	@Bean
	public SecurityFilterChain filterChain(HttpSecurity httpSecurity,@Autowired PersistentTokenRepository repository) throws Exception {
		return httpSecurity
				.csrf().disable()//禁用 CSRF 保护,springsecurity默认开启CSRF保护，需要在index界面使用thymeleaf配置
				.authorizeHttpRequests(auth -> {
					auth.requestMatchers("/static/**","/html/index2.html","/html/register.html","/boot2/register","/html/error.html").permitAll();//放行资源
					auth.requestMatchers("/boot2/hello").authenticated();//登录成功可以访问
//					auth.requestMatchers("/boot2/boss").hasRole("boss");
//					auth.requestMatchers("/boot2/consumer").hasRole("consumer");
					auth.requestMatchers("/favicon.ico").permitAll();//放行 必须配置★★★
					auth.anyRequest().authenticated();
				})
				.formLogin(conf->{				//自定义登录
					conf.loginPage("/html/index2.html");	//登录界面
					conf.loginProcessingUrl("/boot2/doLogin");//处理登录信息的controller，不需要实现，但是和表单的action属性值一致
					conf.defaultSuccessUrl("/boot2/hello",true);//登录成功默认跳转界面
					conf.permitAll();
//					conf.failureHandler((request, response, exception) -> {//登陆失败原因
//	                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//	                    response.getWriter().println("Login failed: " + exception.getMessage());
//	                });
//					conf.successHandler((request, response, authentication) -> {//登录成功后的操作，打印login success
//	                    response.setStatus(HttpServletResponse.SC_OK);
//	                    response.getWriter().println("Login success");
//	                });
					})
				.logout(conf->{				//退出登录功能
					conf.logoutUrl("/boot2/doLogout");
					conf.logoutSuccessUrl("/html/index2.html");
					conf.permitAll();
				})
				.rememberMe(conf->{			//实现记住我功能，默认存一个cookie在浏览器中，保存时间为14天，可以配置保存到数据库，自定义时间
					conf.rememberMeParameter("remember-me");
					//保存在数据库中
					conf.tokenRepository(repository);
					//自定义时间
					conf.tokenValiditySeconds(3600*7);
				})
				.build();
				
	}
}
